import Footer from '@/components/Footer';
import { loginCaptchaUsingPost,userLoginUsingPost,loginCaptchaCheckPost,userRegisterEmailPost,forgetPasswordPost } from '@/services/backend/userController';
import { LockOutlined, UserOutlined, ArrowRightOutlined, CheckOutlined, CloseOutlined,  SmileOutlined, SolutionOutlined,LoadingOutlined} from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { Helmet, history, useModel } from '@umijs/max';
import { message, Tabs, Modal, Steps, Form, Input, Button,Col,Row, Result,Skeleton } from 'antd';
import React, { useState,useEffect } from 'react';
import Settings from '../../../../config/defaultSettings';
import {Link} from "umi";
import styles from './index.less';


const Login: React.FC = () => {
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const [captcha, setCaptcha] = useState<API.Captcha>({});
  const [login, setLogin] = useState<API.UserLogin>({});
  const [forgetPassword, setForgetPassword] = useState<API.UserForgetPassword>({});
  const [captchaModalOpen, setCaptchaModalOpen] = useState(false);//验证码
  const [passwordModalOpen, setPasswordModalOpen] = useState(false);//重置密码
  const [dragState, setDragState] = useState({
    dragging: false, // 表示是否正在拖动
    xOffset: 0,      // 鼠标按下时的 x 偏移量
    yOffset: 0,      // 鼠标按下时的 y 偏移量
    position: { X: 0, Y: 0 }, // 组件的当前位置
  });
  const [isChecked, setIsChecked] = useState(false);//是否验证
  const [checkedRes, setCheckedRes] = useState(false);//验证结果
  const [current, setCurrent] = useState(0);//重置密码步骤
  const [loading, setLoading] = useState(true);
  const [passwordRes, setPasswordRes] = useState(false);//重置密码结果

  const [form] = Form.useForm();
 

  const containerClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    };
  });
  


  // 点击登录按钮
  const click = async() => {
    await handleChaptcha();
    setCaptchaModalOpen(true);
  };

  // 获取验证码图片
  const handleChaptcha =  async () => {
    setIsChecked(false);
    setCheckedRes(false);
    setDragState({
      dragging: false, // 表示是否正在拖动
      xOffset: 0,      // 鼠标按下时的 x 偏移量
      yOffset: 0,      // 鼠标按下时的 y 偏移量
      position: { X: 0, Y: 0 }, // 组件的当前位置
    });
    const {data} = await loginCaptchaUsingPost();
    setCaptcha((preState)=>{
      const newState = {
        ...preState,
        ...data
      }
      return newState;
    });
  }
  const handleMouseDown = (event)=>{
    const { clientX, clientY } = event;
    setDragState(prevState => ({
      ...prevState,
      dragging: true,
      xOffset: clientX - prevState.position.X,
      yOffset: clientY - prevState.position.Y,
    }));
    setIsChecked(false);
  }
  const handleMouseMove  = (event)=>{
    if (!dragState.dragging) return;
    const { clientX, clientY } = event;
    setDragState(prevState => ({
      ...prevState,
      position: {
        X: Math.max(0,  event.clientX - prevState.xOffset),
        Y: captcha.y||0
      },
    }));
    setIsChecked(false);
  } 
  const handleMouseUp = async()=>{
    setIsChecked(true);
    setDragState(prevState => ({
      ...prevState,
      dragging: false,
    }));
    const res = await loginCaptchaCheckPost({point:dragState.position,token:captcha.token});
    if(res.code === 200){
      setCheckedRes(true)
      handleSubmit();
      setTimeout(() => {
        setCaptchaModalOpen(false);
      }, 2000);
    }
    else{
      setCheckedRes(false);
      setTimeout(() => {
        handleChaptcha();
      }, 2000);
    } 
  }

  // 登录
  const handleSubmit = async () => {
    try {
      const res = await userLoginUsingPost(login);
      if (res.code===200){
        const defaultLoginSuccessMessage = '登录成功！';
        localStorage.setItem('tokenValue', res.data?.aToken as string);
        message.success(defaultLoginSuccessMessage);
        // 保存已登录用户信息
        setInitialState({
          ...initialState,
          currentUser:{
            ...res.data,
          }
        });
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
      }
    } 
    catch (error: any) {
      // const defaultLoginFailureMessage = `登录失败，${error.message}`;
      // message.error(defaultLoginFailureMessage);
    }
  };

  //下一步
  const next = async() => {
    const values = await form.validateFields();
    setForgetPassword((preState)=>{
      const newState = {
        ...preState,
        ...values
      }
      return newState;
    });
    setCurrent(current + 1);
  };
  //表格重置
  const reset = () => {
    form.resetFields();
  };
 //重置密码请求
  const handlePassword = async () => {
    if (current === 2) {
      try {
        const res = await forgetPasswordPost(forgetPassword);
        if(res.code === 200){
          setPasswordRes(true);
          form.resetFields();
        }
        else{
          setPasswordRes(false);
        }
       
      } catch (error) {
        setPasswordRes(false);
        // console.error('请求失败:', error);
      }
      setTimeout(()=>{
        setLoading(false);
      },500)
    }
  };
  //获取邮箱验证码
  const handleEmail = async (values:string) => {
    const res = await userRegisterEmailPost({
      userEmail:values
    })
    if(res.code === 200){
      message.success(res.message);
    }
  }
  
  useEffect(() => {
    handlePassword();
  }, [current]); // 依赖

  return (
    <div className={containerClassName}>
      <Helmet>
        <title>
          {'登录'}- {Settings.title}
        </title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" style={{ height: '100%' }} src="http://sems1.oss-cn-beijing.aliyuncs.com/logo.png" />}
          title="短链云"
          subTitle={'只为了帮助你将长URL缩短为易于分享的简洁链接。'}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            click();
            setLogin(values);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码登录',
              },
            ]}
          />
          {type === 'account' && (
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'请输入账号'}
                rules={[
                  {
                    required: true,
                    message: '账号是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                ]}
              />
              <Modal
                title="请完成安全验证"
                centered
                closable={false}
                footer={null}
                open={captchaModalOpen}
                width={358}
                onOk={() => setCaptchaModalOpen(false)}
                onCancel={() => setCaptchaModalOpen(false)}
              >
                <img 
                  className={styles.img} 
                  src={'data:image/PNG;base64,'+captcha?.originalImageBase64}
                  alt="验证码图片" />
                <img 
                  className={styles.puzzle} 
                  src={'data:image/PNG;base64,'+captcha?.jigsawImageBase64}
                  alt="验证码碎片" 
                  style={{
                    left: Math.max(0,dragState.position.X),
                  }}/>
                <div className={styles.slideContainer}>
                  <div 
                    className={`${styles.btn} ${isChecked ? (checkedRes ? styles.success : styles.error):''}`}
                    style={{
                      left: dragState.position.X,
                    }}
                    onMouseDown={handleMouseDown}
                    onMouseMove={handleMouseMove}
                    onMouseUp={handleMouseUp}>
                      {
                        !isChecked ? <ArrowRightOutlined /> : (checkedRes ? <CheckOutlined />:<CloseOutlined />)
                      }
                  </div>
                  <span style={{userSelect: 'none'}}>向右滑动完成验证</span>
                  <div 
                    className={`${styles.slide} ${isChecked ? (checkedRes ? styles.success : styles.error):''}`}
                    style={{
                      width: dragState.position.X+30,
                    }}>
                    </div>
                </div>
              </Modal>
            </>
          )}

          <div
            style={{
              marginBottom: 24,
              display:'flex',
              justifyContent:'space-between',
              alignItems:'center'
            }}
          >
            <a onClick={()=>{setPasswordModalOpen(true);setCurrent(0);setLoading(true)}}>忘记密码?</a>
            <Link to="/user/register">新用户注册</Link>
          </div>
        </LoginForm>
        <Modal
          centered
          closable={false}
          width={480}
          footer={null}
          open={passwordModalOpen}
          onOk={() => setPasswordModalOpen(false)}
          onCancel={() => setPasswordModalOpen(false)}
        >
         <Steps
          current={current}
          items={[
            {
              title: '身份验证',
              icon: <SolutionOutlined />,
            },
            {
              title: '密码重置',
              icon: <UserOutlined />,
            },
            {
              title: '重置完成',
              icon: <SmileOutlined />,
            },
          ]}
        />
        <div className={styles.content}>
          {current ===0 && (
              <Form
                form={form}>
                <Form.Item
                  name="userEmail"
                  rules={[
                    {
                      type: 'email',
                      message: '邮箱不合法！',
                    },
                    {
                      required: true,
                      message: '请输入邮箱！',
                    },
                  ]}
                >
                  <Input size="large" placeholder="请输入邮箱"/>
                </Form.Item>
                <Form.Item >
                  <Row gutter={10}>
                    <Col flex={1}>
                      <Form.Item
                        name="emailCode"
                        rules={[{ required: true, message: '请输入验证码!' }]}
                      >
                        <Input size="large" placeholder="请输入验证码"/>
                      </Form.Item>
                    </Col>
                    <Col flex={1}>
                      <Button size="large" onClick={()=>{
                        handleEmail(form.getFieldValue('userEmail'))
                      }}>发送验证码</Button>
                    </Col>
                  </Row>
                </Form.Item>
              </Form>
          )}
          {
            current === 1 && (
              <Form form={form}>
                 <ProFormText.Password
                    name="newPassword"
                    fieldProps={{
                      size: 'large',
                    }}
                    placeholder="请输入密码"
                    rules={[
                      {
                        required: true,
                        message: '请输入新修改的密码！',
                      },
                      {
                        min: 8,
                        type: 'string',
                        message: '长度不能小于 8',
                      },
                    ]}
                  />
                  <ProFormText.Password
                    name="checkPassword"
                    fieldProps={{
                      size: 'large',
                    }}
                    placeholder="请再次输入密码"
                    rules={[
                      {
                        required: true,
                        message: '请确认新修改的密码！',
                      },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                        if (!value || getFieldValue('newPassword') === value) {
                            return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次输入的密码不一致！'));
                        },
                    }),
                    ]}
                  />
              </Form>
            )
          }
          {
            current === 2 && (loading ? <Skeleton active /> :
            (
              passwordRes ? (
                <Result
                  status="success"
                  title="密码重置成功！"
                  extra={
                    <Button type="primary" size='large' onClick={() => setPasswordModalOpen(false)}>
                      去登录
                    </Button>
                  }
              />
              ):
              (
                <Result
                  status="warning"
                  title="验证码不正确！"
                  extra={[
                    <>
                      <Button type="primary" size='large' onClick={() => {setCurrent(0);setLoading(true)}}>
                        返回
                      </Button>
                      <Button type="primary" size='large' onClick={() => setPasswordModalOpen(false)}>
                        取消
                    </Button>
                    </>
                  ]}
         
              />
              )
            ))
          }
        </div>
        <div style={{ marginTop: 24 }}>
          {current < 2 && (
            <div className={styles.stepBtn}>
              <Button type="primary" onClick={() => next()} style={{marginRight:30}}>
              下一步
              </Button>
              <Button onClick={() => reset()}>
              重置
            </Button>
            </div>
        )}
        </div>
        </Modal>
      </div>
      <Footer />
    </div>
  );
};
export default Login;
